import json
from tabnanny import check
from urllib.parse import ParseResult
from xml.dom.minidom import ProcessingInstruction

# 导入Django核心模块中的序列化器，用于将Django模型转换为其他格式，如JSON、XML等
from django.core import serializers

# 导入Django序列化功能，以便在需要时将模型序列化
from django.core.serializers import serialize
from django.db.models import Q

# 导入HttpResponse和JsonResponse类，用于构建HTTP响应和JSON响应
from django.http import HttpResponse, JsonResponse

# 导入render函数，它用于根据请求和模板渲染网页
from django.shortcuts import render

from django.views import View
# 导入分页类
from django.core.paginator import Paginator
from backend.models import TCheckgroup, TCheckgroupCheckitem
import pymysql

class CheckGroup(View):

    def get(self, request, Page, PageSize):
        # print(Page,PageSize)
        # “直接获取GET请求中'queryString'参数的值”
        queryString = request.GET.get("queryString")
        print(queryString)

        if (queryString == None):
            print("获取检查项列表")
            Check_Group_list = TCheckgroup.objects.filter(is_show=1)
            # 实例化Paginator分页器，将检查项列表Check_Group_list按照PageSize指定的大小进行分页
            paginator = Paginator(Check_Group_list, PageSize)
            # 获取指定页码的数据
            page_skus = paginator.page(Page)
            # 获取分页数据
            # total_page = paginator.num_pages
            # 获取总条数
            total_count = paginator.count
            # 将分页器中的对象列表赋值给checkGroup_list变量
            # checkGroup_list = paginator.object_list
            # 获取指定页码的数据化为JSON格式的字符串，然后将其反序列化为Python对象（列表）
            Check_Group_Json_List = json.loads(serializers.serialize('json', page_skus))
            # print(Check_Group_Json_List)
            data_list = []
            for Check_Group_Json in Check_Group_Json_List:
                data_josn = Check_Group_Json["fields"]
                CheckGroup_id = Check_Group_Json['pk']  # 取检查项id
                data_josn["id"] = CheckGroup_id  # 将检查项id赋值给id字段
                # print(CheckGroup_id)
                data_list.append(data_josn)


            result = {
                "status": "200",
                "message": "获取检查项成功",
                "total_count": total_count,
                "data": data_list

            }
            return JsonResponse(result)
        else:
            print("获取检查项列表")
            # 使用ORM方式，通过名称或代码中包含查询字符串来过滤检查项
            Check_Group_list = TCheckgroup.objects.filter(
                Q(is_show=1) & Q(name__contains=queryString) | Q(code__contains=queryString))
            # 实例化Paginator分页器，将检查项列表Check_Group_list按照PageSize指定的大小进行分页
            paginator = Paginator(Check_Group_list, PageSize)
            # 获取指定页码的数据
            page_skus = paginator.page(Page)
            # 获取分页数据
            # total_page = paginator.num_pages
            # 获取总条数
            total_count = paginator.count
            # 将分页器中的对象列表赋值给checkGroup_list变量
            # checkGroup_list = paginator.object_list
            # 获取指定页码的数据化为JSON格式的字符串，然后将其反序列化为Python对象（列表）
            Check_Group_Json_List = json.loads(serializers.serialize('json', page_skus))
            # print(Check_Group_Json_List)
            data_list = []
            for Check_Group_Json in Check_Group_Json_List:

                data_josn = Check_Group_Json["fields"]
                CheckGroup_id = Check_Group_Json["pk"]
                data_josn["id"] = CheckGroup_id  # 将检查项id赋值给id字段
                # print(CheckGroup_id)
                data_list.append(data_josn)
            result = {
                "status": "200",
                "message": "获取检查项成功",
                "total_count": total_count,
                "data": data_list

            }
            return JsonResponse(result)


    def post(self,request):
        itemIds=request.GET.get("itemIds")
        request_json = request.body.decode("utf-8")
        data_dict = json.loads(request_json)
        res=TCheckgroup.objects.create(
            code=data_dict["code"],
            name=data_dict["name"],
            helpcode=data_dict["helpcode"],
            sex = data_dict["sex"],
            remark=data_dict["remark"],
            attention=data_dict["attention"],
            is_show=1,
        )
        # 将检查项id添加到检查组中,中间表操作
        checikGroup_id=res.checkgroup_id
        Itemid_list=itemIds.split(",")
        for itemId in Itemid_list:
            TCheckgroupCheckitem.objects.create(
                checkgroup_id=checikGroup_id,
                checkitem_id=itemId
            )


        result = {
            "status": "200",
        }
        return JsonResponse(result)
    # 修改检查组信息
    def put(self,request):


        itemIds = request.GET.get("itemIds")
        request_json = request.body.decode("utf-8")
        data_dict = json.loads(request_json)
        print(data_dict)
        checkgroup = TCheckgroup.objects.get(checkgroup_id=data_dict["id"])
        checkgroup_id=checkgroup.checkgroup_id
        conn = pymysql.Connect(
            host="127.0.0.1",
            port=3306, user="root",
            password="123456",
            db="ruici",
            charset="utf8",
            autocommit=True
        )
        cursor = conn.cursor()
        sql = f"UPDATE t_checkgroup set  code='{data_dict['code']}',name='{data_dict['name']}',helpCode='{data_dict['helpcode']}',remark='{data_dict['remark']}', attention = '{data_dict['attention']}' ,sex='{data_dict['sex']}',is_show='1'  where id={checkgroup_id}"
        cursor.execute(sql)
        sql2 = f"delete from t_checkgroup_checkitem where checkgroup_id  = '{checkgroup_id}'"
        cursor.execute(sql2)

        Itemid_list = itemIds.split(",")
        for itemId in Itemid_list:
            TCheckgroupCheckitem.objects.create(
                checkgroup_id=checkgroup_id,
                checkitem_id=itemId
            )

        result = {
            "status": "200",
        }
        return JsonResponse(result)


    def delete(self,request):
        id = request.GET.get("id")
        print("------------------------------------------------------------------")
        print(id)
        checkGroup = TCheckgroup.objects.get(checkgroup_id=id)
        checkGroup.is_show = 0
        checkGroup.save()
        result = {
            "status": "200",
        }
        return JsonResponse(result)

class TCheckgroupCheckitemView(View):
   def get(self,request):
       checkieId = request.GET.get("checkieId")
       print(checkieId)
       conn=pymysql.Connect(
           host="127.0.0.1",
           port=3306,user="root",
           password="123456",
           db="ruici",
           charset="utf8",
           autocommit=True
       )
       cursor=conn.cursor()
       sql=f"select checkitem_id from  t_checkgroup_checkitem where checkgroup_id = '{checkieId}'"

       cursor.execute(sql)
       data_tuple=cursor.fetchall()
       print(data_tuple)
       data_list=[]
       for data in data_tuple:
           data_list.append(data[0])
       print(data_list)
       result = {
           "status": "200",
           "data":data_list
       }
       return JsonResponse(result)



class Tab_GroupView(View):
    def get(self, request, Page):
        Check_Group_list = TCheckgroup.objects.filter(is_show=1)
        Check_Group_Json_List = json.loads(serializers.serialize('json', Check_Group_list))
        data_list = []
        for Check_Group_Json in Check_Group_Json_List:
            # if Check_Item_Json["fields"]["is_del"]==1:

            data_josn = Check_Group_Json["fields"]
            CheckItem_id = Check_Group_Json['pk']  # 取检查项id
            data_josn["id"] = CheckItem_id  # 将检查项id赋值给id字段
            # print(CheckItem_id)
            data_list.append(data_josn)
        result = {
            "status": "200",
            "message": "获取检查项成功",

            "data": data_list

        }
        return JsonResponse(result)



